//
//  YZMSimulateViewController.m
//  YZMicroStock
//
//  Created by apple on 16/12/6.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMSimulateViewController.h"
#import "YZMSegmentViewFixed.h"
#import "YZMControllerManager.h"
#import "YZMStockEntrustView.h"
#import "YZMStockSellView.h"
#import "YZMStockSettlementView.h"
#import "YZMWebViewService.h"
#import "YZClient.h"
#import "YZMConfigureService.h"
#import "YZMAlertView.h"

//NSString *const sYZDShowImageSimFlagDefault = @"YZDShowImageSimFlagDefault";
@interface YZMSimulateViewController ()<YZMSegmentViewDelegate>{
    
    UIImageView *IntroduceImageView;
}
@property (nonatomic, strong) YZMSegmentViewFixed *segmentView;
@property (nonatomic, strong) YZMStockEntrustView *entrustView;
@property (nonatomic, strong) YZMStockSellView *sellView;
@property (nonatomic, strong) YZMStockSettlementView *settlementView;
@property (nonatomic, strong) NSString *stockCode;
@property (nonatomic, strong) NSString *stockName;
@property (nonatomic, strong) UIView *hintView;
@property (nonatomic, strong) UILabel *marketValue; //当前市值
@property (nonatomic, strong) UILabel *amountLB;    //可用点买金额
@property (nonatomic, strong) UILabel *profitandlossLabel;
@property (nonatomic, assign) BOOL unShowErrorFlag;
@property (nonatomic, assign) BOOL unFirstFetchFlag;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) YZMConfigureService *service;
@property (nonatomic, copy) NSString *totalBanlance;
@property (nonatomic, copy) NSString *profitAndLoss;

@end

@implementation YZMSimulateViewController

- (instancetype)init{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed=YES;
        self.title = @"炒股大赛";
    }
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self createObjects];
#ifdef YZMicroStock
    
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"YZDShowImageFlagDefault"]) {
        
        [self addIntroduce];
    }
#endif
}

- (void)addIntroduce{
    
    IntroduceImageView = [UIImageView new];
    [YZMCMInstance.rootTabBarCtrl.view addSubview:IntroduceImageView];
    [IntroduceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(YZMCMInstance.rootTabBarCtrl.view);
    }];
    [IntroduceImageView setImage:[UIImage imageNamed:@"Image_introduce"]];
    IntroduceImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ImageHiden)];
    [IntroduceImageView addGestureRecognizer:dismissTap];
    
}

-(void)ImageHiden{
    
    IntroduceImageView.hidden = YES;
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"YZDShowImageFlagDefault"];
}

-(void)updateTopData{
    [YZClient simU_getBalanceDataSuccess:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            NSString *resultString=topModel.data;
            NSArray *resultArray=[resultString componentsSeparatedByString:@";"];
            self.totalBanlance=resultArray[0];
            self.profitAndLoss=resultArray[1];
            if ([self.profitAndLoss isEqualToString:@"null"]) {
                self.profitAndLoss=@"0.00";
            }
            if ([self.totalBanlance isEqualToString:@"null"]) {
                self.totalBanlance=@"0.00";
            }
            
            self.marketValue.text=self.totalBanlance;
            self.amountLB.text=self.profitAndLoss;
        }else{
            [topModel showMessage];
            self.marketValue.text=@"-- ";
            self.amountLB.text=@"-- ";
        }
    } failure:^(NSError *error) {

            self.marketValue.text=@"-- ";
            self.amountLB.text=@"-- ";
            [error yz_showMessage];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self startTimer];
    [self updateTopData];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [self stopTimer];
}


- (void)startTimer{
    
    switch (self.segmentView.currentIndex) {
    
        case 0:
            [self.entrustView checkIfNeedRequestConfigureData];
            [self.entrustView startTimer];
            break;
            
        case 1:
            [self.sellView startTimer];
            break;
            
        default:
            break;
    }
}

- (void)stopTimer{
    [self.entrustView stopButtonTimer];
    [self.entrustView stopTimer];
    [self.sellView stopTimer];
}

#pragma mark -- YZMSegmentViewDelegate
- (void)segmentView:(YZMSegmentView *)segmentView didScrollToIndexView:(NSInteger)index{
    
    if (index == 0) {
        [self.entrustView checkIfNeedRequestConfigureData];
        [self.entrustView startTimer];
        [self.sellView stopTimer];
        [self updateTopData];

    }else if(index == 1){
        
        [self.sellView startTimer];
        [self.entrustView stopButtonTimer];
        [self.entrustView stopTimer];
        [self updateTopData];
        
    }else if(index == 2){

        [self.sellView stopTimer];
        [self.settlementView fetchSuggestionListFirstPage];
        [self.entrustView stopButtonTimer];
        [self.entrustView stopTimer];
        [self updateTopData];
    }
}

- (void)showEntrustListPage {
    
    [self.segmentView clickAtIndex:0];
}

- (void)showSellListPage{
    
    [self.segmentView clickAtIndex:1];
}

- (void)showSettlementListPage {
    
    [self.segmentView clickAtIndex:2];
}

#pragma mark -- Private Method

- (BOOL)checkNetwork {
    if (kNetworkNotReachability) {
        if (!_unShowErrorFlag) {
            [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
            _unShowErrorFlag = YES;
        }
        return YES;
    }
    return NO;
}

- (void)createObjects{
    [[YZMSIMUConfigureService sharedService]checkIfNeedRequestConfigureWithSuccess:nil];
    WS(ws)
    self.scrollView = [[UIScrollView alloc] init];
    CGSize contentSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height - 64);
    if (iPhone4 || iPhone5) {
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.contentSize = contentSize;
        self.scrollView.bounces = NO;
    }
    
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(ws.view);
    }];
    
    self.hintView = [[UIView alloc] init];
    self.hintView.backgroundColor=[YZMAppStyle colorForMain];
    [self.scrollView addSubview:self.hintView];
    [self.hintView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(ws.scrollView);
        make.height.mas_equalTo(38);
    }];
    
    UILabel *marketLabel=[YZMAppStyle labelWithSmallWhite];
    marketLabel.text=@"体验总金额：";
    [self.hintView addSubview:marketLabel];
    [marketLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.hintView);
        make.left.equalTo(self.hintView).offset(33);
    }];
    
    self.marketValue=[YZMAppStyle labelWithSmallWhite];
    self.marketValue.text=@"--";
    self.marketValue.textColor=[YZMAppStyle colorForYellowButton];
    [self.hintView addSubview:self.marketValue];
    [self.marketValue mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.hintView);
        make.left.equalTo(marketLabel.mas_right);
    }];
    
    self.amountLB=[YZMAppStyle labelWithSmallWhite];
    [self.hintView addSubview:self.amountLB];
    self.amountLB.text=@"--";
    self.amountLB.textColor=[YZMAppStyle colorForYellowButton];
    [self.amountLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.hintView);
        make.right.equalTo(self.hintView.mas_right).offset(-33);
    }];
    
    _profitandlossLabel=[YZMAppStyle labelWithSmallWhite];
    [self.hintView addSubview:_profitandlossLabel];
    _profitandlossLabel.text=@"持仓盈亏：";
    [_profitandlossLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.hintView);
        make.right.equalTo(self.amountLB.mas_left);
    }];
    
    self.segmentView = [YZMSegmentViewFixed new];
    [self.scrollView addSubview:self.segmentView];
    [_segmentView mas_makeConstraints:^(MASConstraintMaker *make){
        make.bottom.left.right.equalTo(ws.scrollView);
        make.width.equalTo(ws.view);
        
        make.top.equalTo(ws.hintView.mas_bottom).offset(14);
        make.height.mas_equalTo(ScreenHeight - 117);
    }];

    self.entrustView = [[YZMStockEntrustView alloc] initWithFrame:self.view.frame  andTradeType:YZM_TRADE_TYPE_FOR_A_STOCK_SIM];
    
    self.sellView = [[YZMStockSellView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain andTradeType:YZM_TRADE_TYPE_FOR_A_STOCK_SIM];
    
    self.settlementView = [[YZMStockSettlementView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain  andTradeType:YZM_TRADE_TYPE_FOR_A_STOCK_SIM];
    
    self.segmentView.delegate = self;
    self.segmentView.titleArray = @[@"点买", @"点卖", @"结算"];
    self.segmentView.viewArray = @[self.entrustView, self.sellView, self.settlementView];
    if (self.stockCode) {
        [self.entrustView updateWithStockCode:self.stockCode andStockName:self.stockName];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
    [self.entrustView endEditing:YES];
}


#pragma mark - controller manager support

#define sYZMTradeSaveStockName @"YZMTradeSimulateSaveStockName"
#define sYZMTradeSaveStockCode @"YZMTradeSimulateSaveStockCode"

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMSimulateViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

#pragma mark - controller manager support
- (void)updateWithParamsManual: (NSDictionary *)params{
    
    [self updateWithParams:params];
    if (self.stockCode) {
        
        [self.entrustView updateWithStockCode:self.stockCode andStockName:self.stockName];
    }
}

- (void)updateWithParams: (NSDictionary *)params
{
    self.service = [YZMConfigureService sharedServiceWithTradeType:YZM_TRADE_TYPE_FOR_A_STOCK_SIM];
    self.stockName = params[@"stockname"];
    self.stockCode  = params[@"stockcode"];
    if (self.stockCode.length == 0) {
        
        NSString *savedCode = [[NSUserDefaults standardUserDefaults] objectForKey: sYZMTradeSaveStockCode];
        NSString *savedName = [[NSUserDefaults standardUserDefaults] objectForKey: sYZMTradeSaveStockName];
        
        if (savedCode.length == 0) {
            
            self.stockCode = @"SH601318";
            self.stockName = @"中国平安";
        }else{
            
            self.stockCode = savedCode;
            self.stockName = savedName;
        }
    }
    
    if (self.stockCode.length != 0) {
        
        [[NSUserDefaults standardUserDefaults] setObject: self.stockCode forKey: sYZMTradeSaveStockCode];
        [[NSUserDefaults standardUserDefaults]  setObject: self.stockName forKey: sYZMTradeSaveStockName];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
